<template>
  <!-- 主内容区域 -->
  <div class="content-area">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><Box /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalMedicines }}</div>
              <div class="stat-label">药品总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon warning">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.lowStockCount }}</div>
              <div class="stat-label">库存预警</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon expired">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.expiredCount }}</div>
              <div class="stat-label">近效期药品</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon value">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                ¥{{ formatAmount(stats.totalValue) }}
              </div>
              <div class="stat-label">库存总值</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">药品名称</div>
          <el-input
            v-model="filters.medicineName"
            placeholder="请输入药品名称"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">药品编号</div>
          <el-input
            v-model="filters.medicineCode"
            placeholder="请输入药品编号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">药品类型</div>
          <el-select
            v-model="filters.medicineType"
            placeholder="请选择药品类型"
            clearable
          >
            <el-option label="西药" value="western" />
            <el-option label="中药" value="chinese" />
            <el-option label="中成药" value="chinese_patent" />
            <el-option label="抗生素" value="antibiotic" />
            <el-option label="生物制品" value="biological" />
            <el-option label="医疗器械" value="medical_device" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">库存状态</div>
          <el-select
            v-model="filters.stockStatus"
            placeholder="请选择库存状态"
            clearable
          >
            <el-option label="充足" value="sufficient" />
            <el-option label="预警" value="warning" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">供应商</div>
          <el-select
            v-model="filters.supplier"
            placeholder="请选择供应商"
            clearable
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.value"
              :label="supplier.label"
              :value="supplier.value"
            />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchMedicines">查询</el-button>
        <el-button type="success" @click="showAddMedicineDialog">
          <el-icon><Plus /></el-icon>
          新增药品
        </el-button>
        <el-button type="warning" @click="showInventoryDialog">
          <el-icon><Edit /></el-icon>
          库存调整
        </el-button>
        <el-button type="danger" @click="exportInventory">
          <el-icon><Document /></el-icon>
          导出库存
        </el-button>
      </div>
    </div>

    <!-- 药品表格 -->
    <div class="medicine-table">
      <div class="table-header">
        <div class="table-title">药品列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table :data="medicines" style="width: 100%" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="药品编号" width="120" />
        <el-table-column label="药品信息" min-width="120">
          <template #default="{ row }">
            <div class="medicine-info">
              <div class="medicine-image">
                <el-image
                  :src="row.image"
                  :alt="row.name"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 6px"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="medicine-details">
                <div class="medicine-name">{{ row.name }}</div>
                <div class="medicine-spec">{{ row.specification }}</div>
                <div class="medicine-manufacturer">{{ row.manufacturer }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            {{ formatMedicineType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column label="库存" width="200">
          <template #default="{ row }">
            <div :class="['stock-info', getStockStatusClass(row)]">
              {{ row.stock }} {{ row.unit }}
              <span v-if="row.stockStatus === 'warning'" class="stock-warning">
                <el-icon><Warning /></el-icon>
              </span>
              <span
                v-else-if="row.stockStatus === 'out_of_stock'"
                class="stock-danger"
              >
                <el-icon><CloseBold /></el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120">
          <template #default="{ row }">
            <div class="price-info">
              <div>进价: ¥{{ formatAmount(row.purchasePrice) }}</div>
              <div>售价: ¥{{ formatAmount(row.sellingPrice) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期" width="120">
          <template #default="{ row }">
            <div :class="['expiry-info', getExpiryStatusClass(row)]">
              {{ row.expiryDate }}
              <span v-if="isExpiringSoon(row)" class="expiry-warning">
                <el-icon><Warning /></el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'active' ? 'success' : 'info'"
              size="small"
            >
              {{ row.status === "active" ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewMedicineDetails(row)"
                >详情</el-button
              >
              <el-button size="small" type="primary" @click="editMedicine(row)">
                编辑
              </el-button>
              <el-button size="small" type="warning" @click="adjustStock(row)">
                调库存
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteMedicine(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 新增/编辑药品对话框 -->
  <el-dialog
    v-model="medicineDialog.visible"
    :title="medicineDialog.isEdit ? '编辑药品信息' : '新增药品'"
    width="800px"
  >
    <el-form
      :model="medicineForm"
      label-width="100px"
      :rules="medicineRules"
      ref="medicineFormRef"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="药品编号" prop="code">
            <el-input
              v-model="medicineForm.code"
              placeholder="请输入药品编号"
              :disabled="medicineDialog.isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品名称" prop="name">
            <el-input
              v-model="medicineForm.name"
              placeholder="请输入药品名称"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="通用名称" prop="genericName">
            <el-input
              v-model="medicineForm.genericName"
              placeholder="请输入通用名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品类型" prop="type">
            <el-select v-model="medicineForm.type" placeholder="请选择药品类型">
              <el-option label="西药" value="western" />
              <el-option label="中药" value="chinese" />
              <el-option label="中成药" value="chinese_patent" />
              <el-option label="抗生素" value="antibiotic" />
              <el-option label="生物制品" value="biological" />
              <el-option label="医疗器械" value="medical_device" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格" prop="specification">
            <el-input
              v-model="medicineForm.specification"
              placeholder="请输入规格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="medicineForm.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input
              v-model="medicineForm.manufacturer"
              placeholder="请输入生产厂家"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplier">
            <el-select
              v-model="medicineForm.supplier"
              placeholder="请选择供应商"
            >
              <el-option
                v-for="supplier in supplierOptions"
                :key="supplier.value"
                :label="supplier.label"
                :value="supplier.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="进价" prop="purchasePrice">
            <el-input-number
              v-model="medicineForm.purchasePrice"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售价" prop="sellingPrice">
            <el-input-number
              v-model="medicineForm.sellingPrice"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="库存数量" prop="stock">
            <el-input-number
              v-model="medicineForm.stock"
              :min="0"
              :precision="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预警数量" prop="warningStock">
            <el-input-number
              v-model="medicineForm.warningStock"
              :min="0"
              :precision="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-input
              v-model="medicineForm.category"
              placeholder="请输入分类"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="批准文号" prop="approvalNumber">
            <el-input
              v-model="medicineForm.approvalNumber"
              placeholder="请输入批准文号"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker
              v-model="medicineForm.productionDate"
              type="date"
              placeholder="选择生产日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期至" prop="expiryDate">
            <el-date-picker
              v-model="medicineForm.expiryDate"
              type="date"
              placeholder="选择有效期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="药品图片" prop="image">
        <el-upload
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImageChange"
        >
          <el-button type="primary">选择图片</el-button>
          <template #tip>
            <div class="el-upload__tip">支持 jpg/png 格式，大小不超过 2MB</div>
          </template>
        </el-upload>
        <div v-if="medicineForm.image" class="image-preview">
          <el-image
            :src="medicineForm.image"
            style="width: 100px; height: 100px; margin-top: 10px"
            fit="cover"
          />
        </div>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="medicineForm.status">
          <el-radio label="active">启用</el-radio>
          <el-radio label="inactive">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="medicineForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入药品描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="medicineDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitMedicineForm">确认</el-button>
    </template>
  </el-dialog>

  <!-- 库存调整对话框 -->
  <el-dialog
    v-model="inventoryDialog.visible"
    :title="`库存调整 - ${currentMedicine?.name}`"
    width="500px"
  >
    <el-form :model="inventoryForm" label-width="100px">
      <el-form-item label="当前库存">
        {{ currentMedicine?.stock }} {{ currentMedicine?.unit }}
      </el-form-item>
      <el-form-item label="调整类型" prop="adjustType">
        <el-radio-group v-model="inventoryForm.adjustType">
          <el-radio label="in">入库</el-radio>
          <el-radio label="out">出库</el-radio>
          <el-radio label="set">设置库存</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="调整数量" prop="quantity">
        <el-input-number
          v-model="inventoryForm.quantity"
          :min="0"
          :precision="0"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="调整原因" prop="reason">
        <el-select v-model="inventoryForm.reason" placeholder="请选择调整原因">
          <el-option label="采购入库" value="purchase" />
          <el-option label="销售出库" value="sale" />
          <el-option label="盘点调整" value="inventory" />
          <el-option label="报损出库" value="damage" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="inventoryForm.notes"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="inventoryDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="confirmInventoryAdjust"
        >确认调整</el-button
      >
    </template>
  </el-dialog>

  <!-- 药品详情抽屉 -->
  <el-drawer
    v-model="detailDrawer.visible"
    title="药品详细信息"
    :direction="'rtl'"
    size="40%"
  >
    <div class="medicine-detail" v-if="currentMedicine">
      <div class="detail-header">
        <el-image
          :src="currentMedicine.image"
          style="width: 80px; height: 80px; border-radius: 8px"
          fit="cover"
        >
          <template #error>
            <div class="image-error-large">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <div class="medicine-basic">
          <h3>{{ currentMedicine.name }}</h3>
          <p>{{ currentMedicine.genericName }}</p>
          <el-tag
            :type="currentMedicine.status === 'active' ? 'success' : 'info'"
          >
            {{ currentMedicine.status === "active" ? "启用" : "停用" }}
          </el-tag>
        </div>
      </div>

      <el-divider />

      <div class="detail-section">
        <h4>基本信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="药品编号">{{
            currentMedicine.code
          }}</el-descriptions-item>
          <el-descriptions-item label="药品类型">{{
            formatMedicineType(currentMedicine.type)
          }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{
            currentMedicine.specification
          }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{
            currentMedicine.unit
          }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{
            currentMedicine.category
          }}</el-descriptions-item>
          <el-descriptions-item label="批准文号">{{
            currentMedicine.approvalNumber
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section">
        <h4>库存信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="当前库存">
            <span :class="getStockStatusClass(currentMedicine)">
              {{ currentMedicine.stock }} {{ currentMedicine.unit }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="预警数量"
            >{{ currentMedicine.warningStock }}
            {{ currentMedicine.unit }}</el-descriptions-item
          >
          <el-descriptions-item label="进价"
            >¥{{
              formatAmount(currentMedicine.purchasePrice)
            }}</el-descriptions-item
          >
          <el-descriptions-item label="售价"
            >¥{{
              formatAmount(currentMedicine.sellingPrice)
            }}</el-descriptions-item
          >
          <el-descriptions-item label="库存状态">
            <el-tag :type="getStockStatusTagType(currentMedicine.stockStatus)">
              {{ formatStockStatus(currentMedicine.stockStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section">
        <h4>供应商信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="生产厂家">{{
            currentMedicine.manufacturer
          }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{
            currentMedicine.supplier
          }}</el-descriptions-item>
          <el-descriptions-item label="生产日期">{{
            currentMedicine.productionDate
          }}</el-descriptions-item>
          <el-descriptions-item label="有效期至">
            <span :class="getExpiryStatusClass(currentMedicine)">
              {{ currentMedicine.expiryDate }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section" v-if="currentMedicine.description">
        <h4>药品描述</h4>
        <p>{{ currentMedicine.description }}</p>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import SiderLift from "@/components/manager/SiderLift.vue";
import TopHeader from "@/components/manager/TopHeader.vue";
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const sidebarOpen = ref(false);
const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");
const filters = reactive({
  medicineName: "",
  medicineCode: "",
  medicineType: "",
  stockStatus: "",
  supplier: "",
});

const stats = reactive({
  totalMedicines: 156,
  lowStockCount: 12,
  expiredCount: 5,
  totalValue: 125800.5,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 供应商选项
const supplierOptions = [
  { value: "S1001", label: "国药控股有限公司" },
  { value: "S1002", label: "上海医药集团" },
  { value: "S1003", label: "华润医药集团" },
  { value: "S1004", label: "九州通医药集团" },
  { value: "S1005", label: "广州医药有限公司" },
];

// 药品数据
const medicines = ref([]);

// 药品对话框相关
const medicineDialog = reactive({
  visible: false,
  isEdit: false,
});

const medicineForm = reactive({
  code: "",
  name: "",
  genericName: "",
  type: "western",
  specification: "",
  unit: "盒",
  manufacturer: "",
  supplier: "",
  purchasePrice: 0,
  sellingPrice: 0,
  stock: 0,
  warningStock: 10,
  category: "",
  approvalNumber: "",
  productionDate: "",
  expiryDate: "",
  image: "",
  status: "active",
  description: "",
});

const medicineRules = {
  code: [{ required: true, message: "请输入药品编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入药品名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择药品类型", trigger: "change" }],
  specification: [{ required: true, message: "请输入规格", trigger: "blur" }],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  manufacturer: [
    { required: true, message: "请输入生产厂家", trigger: "blur" },
  ],
  purchasePrice: [{ required: true, message: "请输入进价", trigger: "blur" }],
  sellingPrice: [{ required: true, message: "请输入售价", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
  expiryDate: [{ required: true, message: "请选择有效期", trigger: "change" }],
};

const medicineFormRef = ref(null);

// 库存调整对话框相关
const inventoryDialog = reactive({
  visible: false,
});

const inventoryForm = reactive({
  adjustType: "in",
  quantity: 0,
  reason: "purchase",
  notes: "",
});

const currentMedicine = ref(null);

// 详情抽屉相关
const detailDrawer = reactive({
  visible: false,
});

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

const resetFilters = () => {
  filters.medicineName = "";
  filters.medicineCode = "";
  filters.medicineType = "";
  filters.stockStatus = "";
  filters.supplier = "";
  loadMedicines();
};

const searchMedicines = () => {
  pagination.currentPage = 1;
  loadMedicines();
};

const loadMedicines = () => {
  // 模拟药品数据
  const mockData = [
    {
      id: "M10001",
      code: "MED001",
      name: "阿莫西林胶囊",
      genericName: "阿莫西林",
      type: "antibiotic",
      specification: "0.25g×24粒",
      unit: "盒",
      manufacturer: "华北制药",
      supplier: "S1001",
      purchasePrice: 8.5,
      sellingPrice: 15.0,
      stock: 45,
      warningStock: 10,
      category: "抗生素类",
      approvalNumber: "国药准字H13020101",
      productionDate: "2023-06-15",
      expiryDate: "2025-06-14",
      image:
        "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp",
      status: "active",
      stockStatus: "sufficient",
      description: "用于敏感菌所致的感染",
    },
    {
      id: "M10002",
      code: "MED002",
      name: "连花清瘟胶囊",
      genericName: "连花清瘟",
      type: "chinese_patent",
      specification: "0.35g×24粒",
      unit: "盒",
      manufacturer: "以岭药业",
      supplier: "S1002",
      purchasePrice: 12.8,
      sellingPrice: 25.0,
      stock: 8,
      warningStock: 5,
      category: "中成药",
      approvalNumber: "国药准字Z20040063",
      productionDate: "2023-08-20",
      expiryDate: "2025-08-19",
      image:
        "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp",
      status: "active",
      stockStatus: "warning",
      description: "清瘟解毒，宣肺泄热",
    },
    {
      id: "M10003",
      code: "MED003",
      name: "胰岛素注射液",
      genericName: "胰岛素",
      type: "biological",
      specification: "10ml:400单位",
      unit: "支",
      manufacturer: "诺和诺德",
      supplier: "S1003",
      purchasePrice: 45.0,
      sellingPrice: 68.0,
      stock: 0,
      warningStock: 3,
      category: "生物制品",
      approvalNumber: "国药准字J20130075",
      productionDate: "2023-05-10",
      expiryDate: "2024-05-09",
      image:
        "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp",
      status: "active",
      stockStatus: "out_of_stock",
      description: "用于糖尿病治疗",
    },
    {
      id: "M10004",
      code: "MED004",
      name: "人参",
      genericName: "人参",
      type: "chinese",
      specification: "50g/袋",
      unit: "袋",
      manufacturer: "吉林人参基地",
      supplier: "S1004",
      purchasePrice: 120.0,
      sellingPrice: 200.0,
      stock: 15,
      warningStock: 5,
      category: "中药材",
      approvalNumber: "",
      productionDate: "2023-09-01",
      expiryDate: "2026-08-31",
      image:
        "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp",
      status: "active",
      stockStatus: "sufficient",
      description: "大补元气，复脉固脱",
    },
    {
      id: "M10005",
      code: "MED005",
      name: "血压计",
      genericName: "电子血压计",
      type: "medical_device",
      specification: "上臂式",
      unit: "台",
      manufacturer: "欧姆龙",
      supplier: "S1005",
      purchasePrice: 180.0,
      sellingPrice: 280.0,
      stock: 6,
      warningStock: 2,
      category: "医疗器械",
      approvalNumber: "械注准20202140001",
      productionDate: "2023-07-15",
      expiryDate: "2028-07-14",
      image:
        "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp",
      status: "active",
      stockStatus: "sufficient",
      description: "家用电子血压测量仪",
    },
  ];

  // 简单的筛选逻辑
  let filteredData = mockData;

  if (filters.medicineName) {
    filteredData = filteredData.filter(
      (item) =>
        item.name.includes(filters.medicineName) ||
        item.genericName.includes(filters.medicineName)
    );
  }

  if (filters.medicineCode) {
    filteredData = filteredData.filter((item) =>
      item.code.includes(filters.medicineCode)
    );
  }

  if (filters.medicineType) {
    filteredData = filteredData.filter(
      (item) => item.type === filters.medicineType
    );
  }

  if (filters.stockStatus) {
    filteredData = filteredData.filter(
      (item) => item.stockStatus === filters.stockStatus
    );
  }

  if (filters.supplier) {
    filteredData = filteredData.filter(
      (item) => item.supplier === filters.supplier
    );
  }

  medicines.value = filteredData;
  pagination.total = filteredData.length;
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadMedicines();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadMedicines();
};

const viewMedicineDetails = (medicine) => {
  currentMedicine.value = medicine;
  detailDrawer.visible = true;
};

const editMedicine = (medicine) => {
  Object.assign(medicineForm, medicine);
  medicineDialog.isEdit = true;
  medicineDialog.visible = true;
};

const adjustStock = (medicine) => {
  currentMedicine.value = medicine;
  Object.assign(inventoryForm, {
    adjustType: "in",
    quantity: 0,
    reason: "purchase",
    notes: "",
  });
  inventoryDialog.visible = true;
};

const deleteMedicine = (medicine) => {
  ElMessageBox.confirm(
    `确定要删除药品 ${medicine.name} 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      medicines.value = medicines.value.filter((m) => m.id !== medicine.id);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const showAddMedicineDialog = () => {
  Object.assign(medicineForm, {
    code: "",
    name: "",
    genericName: "",
    type: "western",
    specification: "",
    unit: "盒",
    manufacturer: "",
    supplier: "",
    purchasePrice: 0,
    sellingPrice: 0,
    stock: 0,
    warningStock: 10,
    category: "",
    approvalNumber: "",
    productionDate: "",
    expiryDate: "",
    image: "",
    status: "active",
    description: "",
  });
  medicineDialog.isEdit = false;
  medicineDialog.visible = true;
};

const showInventoryDialog = () => {
  ElMessage.info("请选择要调整库存的药品");
};

const handleImageChange = (file) => {
  // 模拟图片上传
  medicineForm.image =
    "https://pic4.zhimg.com/80/v2-6c9bb6b4b7c7c41c3c7b4b4b4b4b4b4b_720w.webp";
  ElMessage.success("图片上传成功");
};

const submitMedicineForm = async () => {
  try {
    await medicineFormRef.value.validate();

    // 计算库存状态
    const stockStatus =
      medicineForm.stock === 0
        ? "out_of_stock"
        : medicineForm.stock <= medicineForm.warningStock
        ? "warning"
        : "sufficient";

    if (medicineDialog.isEdit) {
      const index = medicines.value.findIndex((m) => m.id === medicineForm.id);
      if (index !== -1) {
        medicines.value[index] = {
          ...medicineForm,
          stockStatus,
        };
      }
      ElMessage.success("药品信息更新成功");
    } else {
      const newMedicine = {
        ...medicineForm,
        id: `M${medicines.value.length + 10001}`,
        stockStatus,
      };
      medicines.value.unshift(newMedicine);
      ElMessage.success("药品添加成功");
    }

    medicineDialog.visible = false;
    loadMedicines();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const confirmInventoryAdjust = () => {
  if (!currentMedicine.value) return;

  const { adjustType, quantity } = inventoryForm;
  let newStock = currentMedicine.value.stock;

  if (adjustType === "in") {
    newStock += quantity;
  } else if (adjustType === "out") {
    newStock = Math.max(0, newStock - quantity);
  } else if (adjustType === "set") {
    newStock = quantity;
  }

  // 更新库存
  const medicine = medicines.value.find(
    (m) => m.id === currentMedicine.value.id
  );
  if (medicine) {
    medicine.stock = newStock;
    medicine.stockStatus =
      newStock === 0
        ? "out_of_stock"
        : newStock <= medicine.warningStock
        ? "warning"
        : "sufficient";
  }

  ElMessage.success("库存调整成功");
  inventoryDialog.visible = false;
};

const exportData = () => {
  ElMessage.success("数据导出成功");
};

const exportInventory = () => {
  ElMessage.success("库存报表导出成功");
};

const refreshData = () => {
  loadMedicines();
  ElMessage.success("数据已刷新");
};

const formatAmount = (amount) => {
  return Number(amount).toFixed(2);
};

const formatMedicineType = (type) => {
  const typeMap = {
    western: "西药",
    chinese: "中药",
    chinese_patent: "中成药",
    antibiotic: "抗生素",
    biological: "生物制品",
    medical_device: "医疗器械",
  };
  return typeMap[type] || type;
};

const formatStockStatus = (status) => {
  const statusMap = {
    sufficient: "充足",
    warning: "预警",
    out_of_stock: "缺货",
  };
  return statusMap[status] || status;
};

const getStockStatusClass = (medicine) => {
  return {
    "stock-sufficient": medicine.stockStatus === "sufficient",
    "stock-warning": medicine.stockStatus === "warning",
    "stock-danger": medicine.stockStatus === "out_of_stock",
  };
};

const getStockStatusTagType = (status) => {
  const typeMap = {
    sufficient: "success",
    warning: "warning",
    out_of_stock: "danger",
  };
  return typeMap[status] || "info";
};

const getExpiryStatusClass = (medicine) => {
  if (!medicine.expiryDate) return "";

  const expiryDate = new Date(medicine.expiryDate);
  const today = new Date();
  const diffTime = expiryDate.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return {
    "expiry-normal": diffDays > 90,
    "expiry-warning": diffDays <= 90 && diffDays > 0,
    "expiry-danger": diffDays <= 0,
  };
};

const isExpiringSoon = (medicine) => {
  if (!medicine.expiryDate) return false;

  const expiryDate = new Date(medicine.expiryDate);
  const today = new Date();
  const diffTime = expiryDate.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays <= 90 && diffDays > 0;
};

onMounted(() => {
  loadMedicines();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;

    &.total {
      background: linear-gradient(135deg, #409eff, #79bbff);
    }
    &.warning {
      background: linear-gradient(135deg, #e6a23c, #ebb563);
    }
    &.expired {
      background: linear-gradient(135deg, #f56c6c, #f89898);
    }
    &.value {
      background: linear-gradient(135deg, #67c23a, #85ce61);
    }
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.medicine-table {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.medicine-info {
  display: flex;
  align-items: center;

  .medicine-image {
    margin-right: 12px;

    .image-error {
      width: 50px;
      height: 50px;
      background: #f5f7fa;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #c0c4cc;
    }
  }

  .medicine-details {
    .medicine-name {
      font-weight: 500;
      margin-bottom: 4px;
    }

    .medicine-spec {
      font-size: 12px;
      color: #606266;
      margin-bottom: 2px;
    }

    .medicine-manufacturer {
      font-size: 12px;
      color: #909399;
    }
  }
}

.stock-info {
  display: flex;
  align-items: center;
  font-weight: 500;

  &.stock-sufficient {
    color: #67c23a;
  }

  &.stock-warning {
    color: #e6a23c;

    .stock-warning {
      margin-left: 4px;
      color: #e6a23c;
    }
  }

  &.stock-danger {
    color: #f56c6c;

    .stock-danger {
      margin-left: 4px;
      color: #f56c6c;
    }
  }
}

.price-info {
  font-size: 12px;

  div {
    margin-bottom: 2px;
  }
}

.expiry-info {
  display: flex;
  align-items: center;

  &.expiry-normal {
    color: #67c23a;
  }

  &.expiry-warning {
    color: #e6a23c;

    .expiry-warning {
      margin-left: 4px;
      color: #e6a23c;
    }
  }

  &.expiry-danger {
    color: #f56c6c;
  }
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.medicine-detail {
  padding: 20px;

  .detail-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;

    .image-error-large {
      width: 80px;
      height: 80px;
      background: #f5f7fa;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #c0c4cc;
      font-size: 24px;
    }

    .medicine-basic {
      h3 {
        margin: 0 0 8px 0;
        font-size: 18px;
      }

      p {
        margin: 0 0 8px 0;
        color: #606266;
      }
    }
  }

  .detail-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
      font-size: 16px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .filter-item {
    min-width: 150px;
  }

  .stats-cards .el-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .menu-toggle {
    display: block !important;
  }

  .filter-row {
    flex-direction: column;
  }

  .filter-item {
    width: 100%;
  }

  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }

  :deep(.el-drawer) {
    width: 80% !important;
  }

  .medicine-info {
    flex-direction: column;
    align-items: flex-start;

    .medicine-image {
      margin-right: 0;
      margin-bottom: 8px;
    }
  }
}
</style>